﻿using System.Diagnostics;

namespace Sage.Http.Core
{
    /// <summary>
    /// HttpClient单例类，提供全局共享的HttpClient实例
    /// </summary>
    public class HttpClientSingleton
    {
        // 用于存储 HttpClient 的 Lazy 实例
        private static Lazy<HttpClient>? _lazyHttpClient;

        // 用于线程同步的锁对象
        private static readonly Lock _lock = new();

        /// <summary>
        /// 初始化 HttpClient 实例。此方法应在程序启动时调用一次。
        /// </summary>
        /// <param name="timeout">请求超时时间</param>
        /// <param name="baseAddress">基地址 URL</param>
        public static void Initialize(TimeSpan timeout, string baseAddress)
        {
            // 锁定以确保线程安全
            lock (_lock)
            {
                if (_lazyHttpClient != null)
                {
                    Debug.WriteLine("HttpClient 已经被初始化。");
                    throw new InvalidOperationException("HttpClient 已经被初始化。");
                }

                // 创建 Lazy<HttpClient> 实例，延迟初始化 HttpClient
                _lazyHttpClient = new Lazy<HttpClient>(() =>
                {
                    return new HttpClient
                    {
                        Timeout = timeout,
                        BaseAddress = new Uri(baseAddress)
                    };
                }, LazyThreadSafetyMode.ExecutionAndPublication); // 确保线程安全
            }
        }

        /// <summary>
        /// 获取 HttpClient 单例实例。
        /// 在调用此属性之前，必须先调用 Initialize 方法。
        /// </summary>
        public static HttpClient Instance
        {
            get
            {
                if (_lazyHttpClient == null)
                {
                    lock (_lock)
                    {
                        if (_lazyHttpClient == null)
                        {
                            throw new InvalidOperationException("HttpClient 尚未初始化。请先调用 Initialize() 方法。");
                        }
                    }
                }
                return _lazyHttpClient.Value;
            }
        }

        /// <summary>
        /// 释放 HttpClient 实例的资源。
        /// </summary>
        public static void Dispose()
        {
            // 锁定以确保线程安全
            lock (_lock)
            {
                if (_lazyHttpClient?.IsValueCreated == true)
                {
                    _lazyHttpClient.Value.Dispose();
                    _lazyHttpClient = null; // 重置为 null，允许重新初始化
                }
            }
        }
    }
}
